﻿using System;
using System.Collections.Generic;

using SharedGenomics.Core;

namespace SharedGenomics.Workbench.Core
{
    public class CachePresenterInitialisationStage : PresenterInitialisationStage
    {
        private IDictionary<Type, IPresenter> _cachedPresenters;

        public CachePresenterInitialisationStage()
        {
            this._cachedPresenters = new Dictionary<Type, IPresenter>();
        }

        public override bool Initialise(IPresenterInitialisationContext context)
        {
            context.ThrowIfNull("context");
            Type presenterType = context.PresenterType;

            if (presenterType != null && this._cachedPresenters.ContainsKey(presenterType))
            {
                context.Current = this._cachedPresenters[presenterType];
                return false;
            }

            return true;
        }

        public override void PostInitialise(IPresenterInitialisationContext context)
        {
            context.ThrowIfNull("context");

            if (context.AddToCache && !this._cachedPresenters.ContainsKey(context.PresenterType))
            {
                this._cachedPresenters[context.PresenterType] = context.Current;
            }
        }
    }
}
